package edu.nctu.csie.jichang.database.parser;

import java.io.File;
import java.util.List;

import edu.nctu.csie.jichang.database.dbinfo.LoginInfo;
import edu.nctu.csie.jichang.database.model.cell.ColumnFullInfo;
import edu.nctu.csie.jichang.database.model.cell.DBDatabase;
import edu.nctu.csie.jichang.database.model.cell.DBSchema;
import edu.nctu.csie.jichang.database.model.cell.DBTable;
import edu.nctu.csie.jichang.database.model.cell.DBTableHeader;
import edu.nctu.csie.jichang.database.model.connection.AbstractDBConnection;
import edu.nctu.csie.jichang.database.model.connection.IDBConnection;
import edu.nctu.csie.jichang.database.util.DBException;


public class ParseDDL implements IParser{
	
	/**
	 * (non-Javadoc)
	 * @see edu.nctu.csie.jichang.database.parser.IParser#doParse(java.util.LinkedHashMap)
	 */
	public DBDatabase doParse(List<LoginInfo> pConns){
		DBDatabase tDatabase = new DBDatabase();
		for(LoginInfo l :pConns){
			IDBConnection tConn = null;
			try {
				tConn = AbstractDBConnection.getInstance(l);
				tDatabase.addSchema(l.getSchema(),getSchema(l.getSchema(),tConn));
			}finally{
				if(tConn!=null) tConn.close();
			}
		}
		return tDatabase;
	}

	/**
	 * get Schema
	 * @param pName Schema Name
	 * @param pConn Connection
	 * @return DBSchema
	 * @throws Exception if has error
	 */
	protected DBSchema getSchema(String pName,IDBConnection pConn) {
		DBSchema tSchema = new DBSchema(pName);
		if(pConn == null){
			return tSchema;
		}
		for(String s: pConn.getInsertOrder()){
			tSchema.addTable(s, getTable(s,pConn));
		}
		return tSchema;
	}

	/**
	 * get Table
	 * @param pName Table Name
	 * @param pConn Connection
	 * @return DBTable
	 * @throws Exception if has error
	 */
	protected DBTable getTable(String pName, IDBConnection pConn){
		DBTable tTable = new DBTable(pName);
		DBTableHeader tHeader = new DBTableHeader();
		
		tHeader.setPrimaryKey(pConn.getPrimaryKeys(pName));
		tHeader.setUnique(pConn.getUniques(pName));
		tHeader.setIndex(pConn.getIndexs(pName));
		tHeader.setReference(pConn.getReference(pName));
		
		for (ColumnFullInfo c : pConn.getColumnFullInfo(pName)) {
			tHeader.addTableHead(c.getName(), c);
		}
		tTable.addTableHeader(tHeader);
		return tTable;
	}
	
	/**
	 * (non-Javadoc)
	 * @see edu.nctu.csie.jichang.database.parser.IParser#doParse(java.io.File)
	 */
	public DBDatabase doParse(File pFile) {
		throw new DBException("The Object not support this function");
	}
}
